package conf;

import javax.servlet.ServletContextEvent;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sherlocky.config.service.ConfigService;

public class AppContextLoaderListener extends ContextLoaderListener{
	private Log logger = LogFactory.getLog(getClass());
	public void contextInitialized(ServletContextEvent arg0) {
		super.contextInitialized(arg0);
		
		AppContextHolder.setContext(WebApplicationContextUtils.getWebApplicationContext(
				arg0.getServletContext()));
		
		DataSource datasource = (DataSource)WebApplicationContextUtils.getWebApplicationContext(
				arg0.getServletContext()).getBean("dataSource");
		init(datasource);
	}
	
	private void init(DataSource datasource) {
		//更新数据库
		logger.info("----开始部署脚本----");
		DBMigrateUtil.migrateDB(datasource);
		logger.info("----成功部署脚本----");
		
		if((new JdbcTemplate(datasource).queryForList("show character set like '%gbk%'").isEmpty())) {
			Constants.IS_SUPPORT_GBK = false;
		}
		initConstants();
	}
	
	 /**
     * 初始化常量
     */
	private void initConstants() {
		// ConfigService configService = AppContextHolder.getContext().getBean(ConfigService.class);
		// ConfigConstants.SEND_SMS_ATTEMPT_LIMIT = configService.getIntValue("send-sms-attempt-limit");
		// ConfigConstants.REGISTER_ATTEMPT_LIMIT = configService.getIntValue("register-attempt-limit");
		// ConfigConstants.LOGIN_ATTEMPT_LIMIT = configService.getIntValue("login-attempt-limit");
	}
}
